import {
  Component,
  ViewChild,
  Injector,
  Output,
  EventEmitter,
  ElementRef,
} from "@angular/core";
import { ModalDirective } from "ngx-bootstrap";
import {
  ComboboxItemDto,
  MainTaskServiceProxy,
  TaskDto,
  SideTaskServiceProxy,
} from "@shared/service-proxies/service-proxies";
import { AppComponentBase } from "@shared/common/app-component-base";

import * as moment from "moment";
import { finalize } from "rxjs/operators";

@Component({
  selector: "createOrEditOrderModal",
  templateUrl: "./create-or-edit-order-modal.component.html",
})
export class CreateOrEditOrderMainTaskComponent extends AppComponentBase {
  @ViewChild("createOrEditModal") modal: ModalDirective;
  @ViewChild("dueDatePicker") dueDatePicker: ElementRef;

  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  active = false;
  saving = false;
  dueDate = new Date();
  order: TaskDto = new TaskDto();
  orderCategorys: ComboboxItemDto[];
  statuses: ComboboxItemDto[];
  type: number;
  constructor(
    injector: Injector,
    private _mainTaskServiceProxy: MainTaskServiceProxy,
    private _sideTaskServiceProxy: SideTaskServiceProxy
  ) {
    super(injector);
  }

  show(id?: number, type?: number): void {
    this.active = true;
    this.type = type;
    this.order = new TaskDto();
    if (this.type == 1) {
      this._mainTaskServiceProxy.getMainTaskForEdit(id).subscribe((result) => {
        this.order = result;
        this.modal.show();
      });
    } else if (this.type == 2) {
      this._sideTaskServiceProxy.getSideTaskForEdit(id).subscribe((result) => {
        this.order = result;
        this.modal.show();
      });
    }
  }

  save(): void {
    this.saving = true;
    this.order.receptionTime = moment().startOf("day");
    this.order.completionTime = moment(this.dueDate);
    if (this.type == 1) {
      this._mainTaskServiceProxy
        .updateMainTask(this.order)
        .pipe(
          finalize(() => {
            this.saving = false;
          })
        )
        .subscribe(() => {
          this.notify.info(this.l("SavedSuccessfully"));
          this.close();
          this.modalSave.emit(null);
        });
    } else if (this.type == 2) {
      this._sideTaskServiceProxy
        .updateSideTask(this.order)
        .pipe(
          finalize(() => {
            this.saving = false;
          })
        )
        .subscribe(() => {
          this.notify.info(this.l("SavedSuccessfully"));
          this.close();
          this.modalSave.emit(null);
        });
    }
  }

  close(): void {
    this.active = false;
    this.modal.hide();
  }
}
